import 'package:flutter/material.dart';

// 路由操作枚举
enum GMRouteChangeType {
  push,
  pop
}

// 路由监听widget
class GMRouteListenWidget extends StatefulWidget {

  static RouteObserver<PageRoute> routeObserver = RouteObserver<PageRoute>();

  final Widget child;

  // 当前页面展示时的回调
  final Function(GMRouteChangeType)? appearHandler;

  // 当前页面消失时的回调
  final Function(GMRouteChangeType)? disappearHandler;

  // 构造方法
  const GMRouteListenWidget({Key? key, required this.child, this.appearHandler, this.disappearHandler}) : super(key: key);

  @override
  // ignore: library_private_types_in_public_api
  _CWRouteListenWidgetState createState() => _CWRouteListenWidgetState();
}

class _CWRouteListenWidgetState extends State<GMRouteListenWidget> with RouteAware {

  @override
  void didChangeDependencies() {
    ModalRoute? route = ModalRoute.of(context);
    if (route != null) {
      GMRouteListenWidget.routeObserver.unsubscribe(this);
      // 注册监听
      GMRouteListenWidget.routeObserver.subscribe(this, route as PageRoute);
    }
    super.didChangeDependencies();
  }

  @override
  void dispose() {
    // 移除监听
    GMRouteListenWidget.routeObserver.unsubscribe(this);
    super.dispose();
  }

  @override
  void didPush() {
    if (widget.appearHandler != null) {
      widget.appearHandler!(GMRouteChangeType.push);
    }
    super.didPush();
  }

  @override
  void didPop() {
    if (widget.disappearHandler != null) {
      widget.disappearHandler!(GMRouteChangeType.pop);
    }
    super.didPop();
  }

  @override
  void didPushNext() {
    if (widget.disappearHandler != null) {
      widget.disappearHandler!(GMRouteChangeType.push);
    }
    super.didPushNext();
  }

  @override
  void didPopNext() {
    if (widget.appearHandler != null) {
      widget.appearHandler!(GMRouteChangeType.pop);
    }
    super.didPopNext();
  }

  @override
  Widget build(BuildContext context) {
    return widget.child;
  }
}